﻿#!/usr/bin/python
# -*- coding: utf-8 -*-

import re 
from QonsoExtractor import QonsoExtractor
from PyQt4 import QtWebKit, QtCore
from PyQt4.QtNetwork import QNetworkRequest
from DebugLog import DebugLog, DebugFile

class QonsoExtractorBouygues(QonsoExtractor):
   def __init__(self):
      DebugLog("QonsoExtractorBouygues::init")
   
      QonsoExtractor.__init__(self)
      
      self.urlconso = "http://www.espaceclient.bouyguestelecom.fr/ECF/jsf/client/conso-factures/details-conso/viewDetailsConso.jsf"
      self.urlbeforeAuth = "https://www.espaceclient.bouyguestelecom.fr/ECF/jsf/submitLogin.jsf"
      self.urlAuth = "https://www.espaceclient.bouyguestelecom.fr/ECF/jsf/j_security_check;jsessionId="
      self.hostname = "www.espaceclient.bouyguestelecom.fr"

   def Authenticate(self, idCorrelation):
      DebugLog("QonsoExtractorBouygues::Authenticate")
      self.SetStatus('INFO', 'Authentification...')
      self.SetProgressRange(10,20)

      request = self.PrepareRequest()
      request.setUrl( QtCore.QUrl(self.urlAuth+idCorrelation) ) 
      
      cookies = self.manager.cookieJar().cookiesForUrl(QtCore.QUrl("http://"+self.hostname))
      for cookie in cookies:
         if cookie.name()=="JSESSIONID":
            request.setRawHeader("Cookie", "testcookie; "+cookie.name()+"="+cookie.value())

      params = QtCore.QUrl()
      params.addQueryItem("j_username", self.login)
      params.addQueryItem("j_password", self.password)
      params.addQueryItem("application_name", "ESPACE_CLIENT_WEB_FORFAIT")
      params.addQueryItem("idCorrelation", idCorrelation)

      self.PostRequest(params, request)
      
   def DoReadResponse(self, reply):
      DebugLog("QonsoExtractorBouygues::DoReadResponse")
      
      request = QNetworkRequest()
      page = QtWebKit.QWebPage()
      frame = page.currentFrame()

      # Phase d'initialisation, on va extraire 'idCorrelation', et on lance l'authentification avec
      DebugLog("authentication=="+self.authentication)
      
      if self.authentication=='Init':
         html = reply.readAll()
         frame.setHtml(str(html))
         idCorrelation = frame.findFirstElement('input[name=idCorrelation]').attribute('value')
         self.authentication = 'InProgress'
         self.Authenticate(idCorrelation)
      
      # Authentification en cours, on récupère la page de redirection, et on fait une redirection
      elif self.authentication == 'InProgress':
         possibleRedirectUrl = reply.attribute(QNetworkRequest.RedirectionTargetAttribute)
         redirectUrl = possibleRedirectUrl.toUrl()
         request.setUrl( redirectUrl ) 
         self.manager.get(request)
         self.authentication = 'Redirecting'

      # Gestion des redirections, il peut y en avoir plusieurs à la suite
      elif self.authentication == 'Redirecting':
         html = str(reply.readAll())
         possibleRedirectUrl = reply.attribute(QNetworkRequest.RedirectionTargetAttribute)
         redirectUrl = str(possibleRedirectUrl.toUrl().toString())

         DebugLog(redirectUrl+str(redirectUrl.find("submitLoginError")))
         
         if redirectUrl and redirectUrl.find("submitLoginError")>0:
            self.SetStatus('ERROR', "Erreur avec vos identifiants")
            self.CheckForErrors(html)
            return
            
         else:
            DebugLog("No more redirection")
            # pas de redirection, on vérifie s'il n'y a pas d'erreur dans la page
            html = str(reply.readAll())
            
            if not self.CheckForErrors(html):
               # pas d'erreur, c'est Lesieur, on peut charger la page des consommations
               self.UpdateConso()
               return
            
         self.manager.get(request)
      
   def CheckForErrors(self, html):
      DebugLog("QonsoExtractorBouygues::CheckForErrors")
      DebugFile(html)
      r = re.compile('<div class="erreur">(.+?)</div>')
      res = r.search(html)
               
      if res:
         DebugLog("Erreur trouvée : "+str(res.groups()) )
         error = re.sub( "<.*?>", "", res.group(1)).strip()
         
         if error:
            self.SetStatus('ERROR', error)
            return True
         else:
            DebugLog("Pas d'erreur en fait...")
            return False
      return False
      
   def DoExtractDatas(self, html):
      DebugLog("QonsoExtractorBouygues::DoExtractDatas")

      if self.CheckForErrors(html):
         return
      
      self.SetProgress(10, 100)
      # Date de la dernière communication
      date = ""
      res = re.search('DetailConsoDateConso".*?>(\d{1,2}/\d{1,2}/\d{2,4})<', html)
      if res:
         date = res.group(1)
      DebugLog("date=%s"%date)

      self.SetProgress(20, 100)
      # Heure de la dernière communication
      time = ""
      res = re.search('DetailConsoHeureConso".*?>(\d{1,2}h\d{1,2})<', html)
      if res:
         time = res.group(1)
      DebugLog("time=%s"%time)

      if date and time:
         self.model.lastTime = "Ma consommation au "+date + " &agrave; " + time

      self.SetProgress(30, 100)
      # Date de la prochaine facture
      res = re.search('dateEmissionFacture".*?>(\d{1,2}/\d{1,2}/\d{2,4})<', html)
      if res:
         date = res.group(1)
         DebugLog("date f=%s"%date)
         self.model.facture = "Prochaine facture : "+date+" au soir"
      else:
         DebugLog("date f pas trouve")

      self.SetProgress(40, 100)
      # Conso Voix
      DebugLog("_______________________________________________\nConso voix")
      DebugLog("-----------------------------------------------\n")
      res = re.search("(?:Vous n'avez pas encore profité de)? votre [Ff]orfait (.+?) de ((?:\s*\d{1,2}\s*[Hh])?\s*(?:\d{1,3}\s*(?:mi?n)))" , html)
      if res:
         DebugLog(res.groups())
         self.model.SetForfait( res.group(1) )
         self.model.SetConsoVoixMax( res.group(2) )
         self.model.SetConsoVoix( "0" )
      
      self.SetProgress(50, 100)
      res = re.search("votre [Ff]orfait (.+) de %smin.+vous avez consomm.+?%s" %(self.hmReS, self.hmReS), html)
      if res:
         DebugLog(res.groups())
         self.model.SetForfait( res.group(1) )
         self.model.SetConsoVoixMax( res.group(2) )
         self.model.SetConsoVoix( res.group(3) )
         
      # Conso Data
      DebugLog("_______________________________________________\nConso data")
      DebugLog("-----------------------------------------------\n")
      res = re.search('class="gv2_detailsConso_typo_orange_gras".*?>([\d,]+?)&nbsp;Mo', html)
      if res:
         DebugLog(res.groups())
         self.model.SetConsoData( res.group(1) )
         
      res = re.search('Lorsque votre débit aura atteint&nbsp;(\d+).*?Mo', html)
      if res:
         DebugLog(res.groups())
         self.model.SetConsoDataMax( res.group(1) )
      else:
         if self.model.forfait.find("Neo")>-1 or self.model.forfait.find("Evasio")>-1:
            self.model.SetConsoDataMax("500")

      self.SetProgress(60, 100)
      # Conso Voix Supplémentaire
      if self.model.forfait.find("Evasio")>-1:
         DebugLog("_______________________________________________\nConso voix Supplémentaire")
         DebugLog("-----------------------------------------------\n")
         res = re.search("Sur votre enveloppe.+vous avez consomm.+%s"%self.hmReS, html)
         if res:
            DebugLog(res.groups())
            self.model.SetConsoVoixSupp( res.group(1) )
            self.model.SetConsoVoixSuppMax( self.model.GetConsoVoixMax('str') )

      self.SetProgress(70, 100)
      # SMS
      DebugLog("_______________________________________________\nConso SMS")
      DebugLog("-----------------------------------------------\n")
      res = re.search("pas encore profité de votre [Ff]orfait de (\d+) SMS", html)
      if res:
         DebugLog(res.groups())
         self.model.SetConsoSMS( '0' )
         self.model.SetConsoSMSMax( res.group(1) )
      else:
         res = re.search("Sur votre [Ff]orfait de (\d+) SMS.+vous avez consomm.+?(\d+) SMS", html)
         if res:
            DebugLog(res.groups())
            self.model.SetConsoSMS( res.group(2) )
            self.model.SetConsoSMSMax( res.group(1) )

      self.SetProgress(80, 100)
      # Bonus SMS
      DebugLog("_______________________________________________\nBonus SMS")
      DebugLog("-----------------------------------------------\n")
      res = re.search("avez consommé (.+?) de votre bonus de (\d+) SMS", html)
      if res:
         DebugLog(res.groups())
         if res.group(1)=='la totalité':
            self.model.SetConsoSMSSupp( res.group(2) )
         else:
            self.model.SetConsoSMSSupp( res.group(1) )
         self.model.SetConsoSMSSuppMax( res.group(2) )
      else:
         res = re.search("pas encore.+?votre bonus de (\d+) SMS", html)
         if res:
            DebugLog(res.groups())
            self.model.SetConsoSMSSupp( '0' )
            self.model.SetConsoSMSSuppMax( res.group(1) )
         else:
            res = re.search("votre bonus de (\d+) SMS.+?vous avez consommé.+?(\d+) SMS", html)
            if res:
               DebugLog(res.groups())
               self.model.SetConsoSMSSupp( res.group(2) )
               self.model.SetConsoSMSSuppMax( res.group(1) )
         
      self.SetProgress(90, 100)
      # Report de minutes
      DebugLog("_______________________________________________\nReport de minutes")
      DebugLog("-----------------------------------------------\n")
      res = re.search("[Rr]eport de minutes.*Pas de report", html)
      if not res:
         res = re.search("[Rr]eport de minutes.*?<span>.*?%s.*?</span>"%self.hmReS, html)
         if res:
            self.model.SetReport( res.group(1) )
            DebugLog("report = "+res.group(1))
         else:
            res = re.search("[Rr]eport de minutes de\s*%s" % self.hmReS, html)
            if res:
               self.model.SetReport( res.group(1) )
               DebugLog("report = "+res.group(1))

      self.SetProgress(99, 100)
      # Hors forfait
      DebugLog("_______________________________________________\nHors forfait")
      DebugLog("-----------------------------------------------\n")
      reHForfait = re.compile(u"[Mm]ontant [Hh]ors [Ff]orfait.*?(\d+[\.,]?\d*)\s", re.DOTALL)
      res = reHForfait.search(html)
      if res:
         self.model.SetConsoHorsForfait( res.group(1) )
         DebugLog("hforfait = "+res.group(1))
      